﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Colors;
using Autodesk.AutoCAD.Runtime;
using System.Collections.Generic;

namespace BasicTools
{
    public class TestCommand : AutoCADBase
    {
        [CommandMethod("YX")]
        public void IsolateEntitiesByColor()
        {
            PromptEntityResult per = _ed.GetEntity("请选择一个实体");
            if (per.Status != PromptStatus.OK) return;
            ObjectId id = per.ObjectId;
            using (var trans = _db.TransactionManager.StartTransaction())
            {
                if (id != ObjectId.Null)
                {
                    Entity entity = trans.GetObject(id, OpenMode.ForRead) as Entity;
                    ObjectId layerId = entity.LayerId;
                    Color color = entity.Color;

                    LayerControlTools.DisplayOrHideEntitiesByColor(color, layerId, DisplayOrHide.Isolate);
                }
                trans.Commit();
            }
        }

        [CommandMethod("YY")]
        public void HideEntitiesByColor()
        {
            PromptEntityResult per = _ed.GetEntity("请选择一个实体");
            if (per.Status != PromptStatus.OK) return;
            ObjectId id = per.ObjectId;
            using (var trans = _db.TransactionManager.StartTransaction())
            {
                if (id != ObjectId.Null)
                {
                    Entity entity = trans.GetObject(id, OpenMode.ForRead) as Entity;
                    ObjectId layerId = entity.LayerId;
                    Color color = entity.Color;

                    LayerControlTools.DisplayOrHideEntitiesByColor(color, layerId, DisplayOrHide.Hide);
                }
                trans.Commit();
            }
        }

        [CommandMethod("QX")]
        public void DisplayAllEntities()
        {
            using (var trans = _db.TransactionManager.StartTransaction())
            {
                try
                {
                    //打开所有图层
                    var layers = _db.GetAllLayers();
                    foreach (var layer in layers)
                    {
                        (trans.GetObject(layer.Id, OpenMode.ForWrite) as LayerTableRecord).IsHidden = false;
                    }
                    //显示所有实体
                    var entities = _db.GetEntsInModelSpace();
                    foreach (var entity in entities)
                    {
                        (trans.GetObject(entity.Id, OpenMode.ForWrite) as Entity).Visible = true;
                    }

                    trans.Commit();
                }
                catch (System.Exception ex)
                {
                    Application.ShowAlertDialog(ex.Message.ToString());
                    trans.Abort();
                }
            }
        }
    }
}
